import React, { useState, forwardRef, useCallback } from "react";
import { ScrollView } from "@tarojs/components";
import classnames from "classnames";
import "./index.less";

export interface CustomScrollViewProps {
  className?: string;
  styles?: React.CSSProperties;
  onRefresh?: (...args) => Promise<void>;
  children: React.ReactNode;
}

export const CustomScrollView = forwardRef<{}, CustomScrollViewProps>((props, ref) => {
  const { className, styles, onRefresh } = props;
  const [refreshing, setRefreshing] = useState<boolean>(false);
  // 下拉刷新
  const onPulldownRefresh = useCallback(async () => {
    setRefreshing(true);
    if (onRefresh) {
      await onRefresh();
    }
    setTimeout(() => {
      setRefreshing(false);
    });
  }, [onRefresh]);

  return (
    <ScrollView
      className={classnames("custom-scroll-view", className)}
      style={styles}
      scrollY
      refresherEnabled
      refresherTriggered={refreshing}
      onRefresherRefresh={onPulldownRefresh}
      ref={ref}
      scrollWithAnimation
    >
      {props.children}
    </ScrollView>
  );
});
